package cn.ly.link.iterator;

import cn.ly.link.Node;

public class LinkList<E> {
	
	private Node first;
	
	public LinkList(){
		this.first = null;
	}
	
	public Node getFirst(){
		return this.first;
	}
	
	public void setFirst(Node node){
		this.first = node;
	}
	
	public void insertFirst(E e){
		Node newNode = new Node(e);
		newNode.next = this.first;          //第一个进入的节点的next是first，first是null，所以第一节点的next是null
		this.first = newNode;               //新来的节点放在链表头的位置，下一次新节点进来指向链表头节点，然后再把自己变成表头节点
	}
	
	public boolean isEmpty(){
		return first == null;
	}
	
	public Node deleteFirst(){
		Node temp = this.first;   
		this.first = this.first.next;       //因为删除数据，是删除表头的节点，所以，把表头节点变成表头的next节点即可，
		return temp;                        //相当于表头节点的引用被 表头的next覆盖了，这样要被删除的表头节点的引用就没有了，
	}                                       //会被来及回收，向当于删除，所以快
	
	
	public Node find(E e){
		Node cur = this.first;
		while(cur != null){
			if(cur.data == e){
				return cur;
			}
			cur = cur.next;
		}
		return null;
	}
	
	public Node delete(E e){
		Node cur = this.first;
		Node preNode = this.first;
		while(cur != null){
			if(cur.data != e){
				preNode = cur;
				cur = cur.next;
			}else{
				if(this.first.data == e){
					this.first = cur.next;
				}else{
					preNode.next = cur.next;
				}
				return cur;
			}
		}
		return null;
	}
	
	public void display(){
		Node cur = first;
		while(cur != null){
			cur.display();
			cur = cur.next;
		}
		System.out.println();
	}
	
	
	
}
